package com.rem.flink.flink8State;

import com.rem.flink.flink2Source.ClickSource;
import com.rem.flink.flink2Source.Event;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

/**
 * 按键分区状态 ValueState
 * 周期性(10s)统计每个用户的pv
 *
 * @author Rem
 * @date 2022-10-24
 */

public class ValueStateTest {

    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        SingleOutputStreamOperator<Event> stream = env.addSource(new ClickSource())
                .assignTimestampsAndWatermarks(WatermarkStrategy.<Event>forMonotonousTimestamps()
                        .withTimestampAssigner((element, recordTimestamp) -> element.getTimestamp()));


        stream.print("input");

        stream.keyBy(Event::getUser)
                .process(new KeyedProcessFunction<String, Event, String>() {
                    /**
                     * 统计每个user 访问量 存放饿的state
                     */
                    ValueState<Long> countState;
                    /**
                     * 定时器 存在 每隔10s 统计一次
                     */
                    ValueState<Long> timerTsState;

                    @Override
                    public void open(Configuration parameters) throws Exception {
                        countState = super.getRuntimeContext().getState(new ValueStateDescriptor<>("count", Long.class));
                        timerTsState = super.getRuntimeContext().getState(new ValueStateDescriptor<>("timerTs", Long.class));
                    }

                    @Override
                    public void processElement(Event event, Context ctx, Collector<String> out) throws Exception {
                        //统计数量
                        Long count = countState.value();
                        if (count == null) {
                            countState.update(1L);
                        } else {
                            countState.update(count + 1L);
                        }

                        //注册定时器 10s /次
                        if (timerTsState.value() == null) {
                            ctx.timerService().registerEventTimeTimer(event.getTimestamp() + 10 * 1000L);
                            timerTsState.update(event.getTimestamp() + 10 * 1000L);
                        }
                    }

                    @Override
                    public void onTimer(long timestamp, OnTimerContext ctx, Collector<String> out) throws Exception {
                        out.collect(ctx.getCurrentKey() + " pv: " + countState.value());
                        // 清空状态
                        timerTsState.clear();

                    }
                }).print();

        env.execute();

    }
}
